from flask import Blueprint, abort
from flask import Flask, flash, request, redirect, url_for, current_app, jsonify
from flask.helpers import send_from_directory, send_file
import pymongo
from werkzeug.utils import secure_filename
from flask_login import login_user, logout_user, current_user
from paddy_doctor.model.user import User
from flask_login.utils import login_required
import json
import os
import datetime
from dateutil import parser
from paddy_doctor.model.database import mongo

mod = Blueprint('user', __name__)

@mod.route('/login', methods=['POST'])
def login():
    info = json.loads(request.data)
    username = info.get('username', 'guest')
    password = info.get('password', '')
    user = User.login(username=username, password=password)
    if user:
        login_user(user)
        return jsonify({"status": 'success', "user": user.to_json()})
    else:
        return jsonify({"status": 'error',
                        "message": "密码错误"})


@mod.route('/register', methods=['POST'])
def register():
    info = json.loads(request.data)
    username = info.get('username', 'guest')
    password = info.get('password', '')
    user = User.register(username=username, password=password)
    if user:
        login_user(user)
        return jsonify({"status": 'success', "user": user.to_json()})
    else:
        return jsonify({"status": 'error',
                        "message": "Username or Password Error"})


@mod.route('logout',  methods=['POST'])
@login_required
def logout():
    User.logout(current_user)
    logout_user()
    return jsonify(**{'status': 'success',
                      'data': {'message': 'logout success'}})


@mod.route('history',  methods=['POST'])
@login_required
def history():
    if current_user.is_authenticated:
        result = mongo.db.record.find({'userid': current_user.id}, {'_id': 0}).sort('time', direction=pymongo.DESCENDING)
        return jsonify({'status': 'success', 'result': list(result)})
    return jsonify({'status': 'success', 'result': []})


@mod.route('image/<fileid>',  methods=['POST'])
@login_required
def getImage(fileid):
    # 检查是否属于该用户
    result = mongo.db.record.find_one({'userid': current_user.id, 'fileid': fileid})
    if result != None:
        f = os.path.join(current_app.config['UPLOAD_FOLDER'], fileid + result['fileext'])
        # 这里send_file和存图片时的base dir不一样，是项目目录，这多少有点……
        # f = os.path.join('..', current_app.config['UPLOAD_FOLDER'])
        # f = open(os.path.join(current_app.config['UPLOAD_FOLDER'], fileid + result['fileext']), mode='r')
        # return send_file(f, as_attachment=False, attachment_filename=fileid + result['fileext'])
        return send_from_directory(current_app.config['UPLOAD_FOLDER'], fileid + result['fileext'])
    else:
        abort(404)


@mod.route('/profile', methods=['POST'])
@login_required
def updateProfile():
    info = json.loads(request.data)
    # TODO 数据合法性检验
    username = info.get('username')
    password = info.get('password')
    location = info.get('location')
    updateDocument = {}
    if username != None and username != '':
        updateDocument['username'] = username
        current_user.username = username
    if password != None and password != '':
        updateDocument['password'] = password
        current_user.password = password
    if location != None and location != '':
        updateDocument['location'] = location
        current_user.location = location
    if len(updateDocument) >= 1:
        mongo.db.user.update_one({'id': current_user.id}, {'$set': updateDocument})
    return jsonify({"status": "success"})

@mod.route('trending',  methods=['POST'])
@login_required
def getTrending():
    user = mongo.db.user.find_one({'id': current_user.id})
    if user == None:
        return jsonify({'status': 'error', 'message': 'user not found'})
    city = user['location']
    if city == 'unknown':
        return jsonify({'status': 'error', 'message': 'location not set'})
    # result = mongo.db.record.aggregate([
    #     {'$match':{'location':city}},
    #     {'$project':{'day':{'$substr': ["$time", 0, 10] }}},
    #     {'$group':{'_id':"$day", 'number':{'$sum': 1}}},
    #     {'$sort': {'_id':-1}},
    #     {'$limit': 7} ])
    lastWeek = []
    for i in range(7, 0, -1):
        date = parser.parse(str(datetime.datetime.now().date() - datetime.timedelta(days=i)))
        day = {}
        day['_id'] = date
        day['offset'] = i
        result = mongo.db.record.find({'location':city, 'time': {'$gte': date, '$lt': date + datetime.timedelta(days=1)}}).count()
        day['number'] = result
        lastWeek.append(day)
    # print(lastWeek)
    return jsonify({"status": "success", "result": lastWeek})

@mod.route('trending/<modelid>',  methods=['POST'])
@login_required
def getTypeTrending(modelid):
    user = mongo.db.user.find_one({'id': current_user.id})
    if user == None:
        return jsonify({'status': 'error', 'message': 'user not found'})
    city = user['location']
    if city == 'unknown':
        return jsonify({'status': 'error', 'message': 'location not set'})
    lastWeek = []
    for i in range(7, 0, -1):
        date = parser.parse(str(datetime.datetime.now().date() - datetime.timedelta(days=i)))
        day = {}
        day['_id'] = date
        day['offset'] = i
        result = mongo.db.record.aggregate([
            {'$match': {'location':city, 'modelid': modelid, 'time': {'$gte': date, '$lt': date + datetime.timedelta(days=1)}}},
            {'$group': {'_id': '$result', 'number': {'$sum': 1}}}
        ])
        day['number'] = list(result)
        lastWeek.append(day)
    # print(lastWeek)
    return jsonify({"status": "success", "result": lastWeek})